package com.example.dbcenter.conf.excutor;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor;
import com.example.dbcenter.conf.MySqlOutputVisitorWithText;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.SerializationUtils;

public abstract class DbExcutor {
    public static final int SELECT = 0;
    public static final int INSERT = 1;
    public static final int UPDATE = 2;
    public static final int REMOVE = 3;
    protected static final String DB = "db";
    protected String collectionName;
    protected DbExcutor.DBTYPE SQLDBType;


    public DbExcutor(){
        this.SQLDBType = DBTYPE.MYSQL;
    }

    public void setDbtype(DBTYPE type) {
        this.SQLDBType = type;
    }

    public abstract String parseQueryFromMongo();
    public abstract String parseQueryFromSql();

    public String parseQueryFromSql(DBTYPE type) {
        setDbtype(type);
        return parseQueryFromSql();
    }

    public  String parseQueryFromMongo(Query query) {
        String jsonQuery = "";
        if(query != null) {
            jsonQuery = SerializationUtils.serializeToJsonSafely(query.getQueryObject());
        }
        return jsonQuery;
    }
    protected String getSql(SQLStatement statement) {
        StringBuilder sql = new StringBuilder();
        SQLASTOutputVisitor visitor = null;
        switch (this.SQLDBType) {
            case MYSQL:
                visitor = new MySqlOutputVisitorWithText(sql);
                break;
        }
        statement.accept(visitor);
        return sql.toString().replace("\n", " ").replace(";", "");
    }

    public static enum DBTYPE {
        MYSQL,
        ORACLE,
        SQLSERVER,
        SQLITE,
        OTHERSQL;
        private DBTYPE() {
        }
    }
}
